package com.qiyu.dubbo.config.starter.cluster;


import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.Router;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.cluster.support.FailoverClusterInvoker;

import java.lang.reflect.Field;
import java.util.List;

/**
 * dubbo调用接口之前需要先通过cluster这个组件，在这里做重载，给他注入相关的router配置
 *
 * @author linhao
 * @date created in 10:22 下午 2020/11/21
 */
public class ZoneAwareCluster implements Cluster {

    @Override
    public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
        AbstractDirectory ad = (AbstractDirectory) directory;
        RouterChain routerChain = ad.getRouterChain();
        try {
            Field routerField = routerChain.getClass().getDeclaredField("routers");
            routerField.setAccessible(true);
            List<Router> routers = (List<Router>) routerField.get(routerChain);
            System.out.println(routers.toArray());
            routers.add(new LimitIpRouter());
            return new FailoverClusterInvoker<>(directory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
